package com.wan.net.rpc.service;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.digest.MD5;
import com.wan.net.config.HostAndPort;

import java.util.HashMap;
import java.util.Map;

/**
 * 服务数据包装
 * @author wwh
 * @date 2022/6/17 11:00
 */
public class RpcService {
    public final static String VERSION   = "version";  //版本号
    public final static String DESC      = "desc";     //描述
    public final static String IMPLEMENT = "implement";//实现类全限定名

    /** 提供服务的接口 */
    private Class<?> serviceInterface;
    /** 服务地址 */
    private HostAndPort hostAndPort;
    /** 额外参数 */
    private final Map<String,Object> params;

    private RpcService(){
        params = new HashMap<>();
    }

    public static RpcService create(){
        return new RpcService();
    }

    public void copyAt(RpcService rpcService){
        if(rpcService.serviceInterface != null){
            this.serviceInterface = rpcService.serviceInterface;
        }
        if(rpcService.hostAndPort != null){
            this.hostAndPort = rpcService.hostAndPort;
        }
        this.params.putAll(rpcService.params);
    }

    public Class<?> getServiceInterface() {
        return serviceInterface;
    }

    public HostAndPort getHostAndPort() {
        return hostAndPort;
    }

    public RpcService addParam(String name,Object value){
        this.params.put(name,value);
        return this;
    }

    public RpcService hostAndPort(HostAndPort hostAndPort){
        this.hostAndPort = hostAndPort;
        return this;
    }

    public RpcService serviceInterface(Class<?> serviceInterface){
        this.serviceInterface = serviceInterface;
        return this;
    }

    public Map<String, Object> getParams() {
        return params;
    }

    /** 获取唯一的md5拼接值 */
    public String uniqueMD5(){
        String data = hostAndPort + params.toString();
        String md5Hex = DigestUtil.md5Hex(data);
        return serviceInterface.getName() + "-" + md5Hex;
    }

    @Override
    public String toString() {
        return "[rpc服务]->[interface=" + serviceInterface.getName() +
                ",address=" + hostAndPort +
                ",params=" + params + "]";
    }
}
